package com.see51.demo.see51demo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.see51.demo.see51demo.Model.DevFileInfo;
import com.see51.sdk.java.I51SeeListener;
import com.see51.sdk.java.Jni51SeeSdk;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class DivDirActivity extends AppCompatActivity {


    //文件下载完成通知
    public void    OnDownFileOver(int devHandel,String fileName)
    {

    }
    //设备句柄
    private int           devHandle = 0;

    private String         m_strDevId;
    private String         m_strDevTurnIp ;
    class DirItem
    {
        public String Par="";
        public String filename="";
        public int isdir=0;
        public int filesize=0;
    }

    class ListDirAdapter extends BaseAdapter implements AdapterView.OnItemClickListener
    {

        private List<DirItem> DataList = new ArrayList<DirItem>();//实体类
        public void Add(DirItem item)
        {
            DataList.add(item);
        }
        public void Clear()
        {
            DataList.clear();
        }

        //文件下载
        View.OnClickListener BtnDownClickListener = new View.OnClickListener()
        {
            public void onClick(View v)
            {
                DirItem Item = DataList.get((Integer) v.getTag());
                Jni51SeeSdk sdk = new Jni51SeeSdk();
                String key=m_strDevId+"_"+Item.filename;
                final See51App app = (See51App)getApplication();
               if(app.HasDownInfo( key))
               {

               }else {
                   //文件下载
                   String filepath = Item.filename;
                   Log.d("filepath：", filepath);
                   String Info = sdk.JniGetDownDevFile(devHandle, filepath, Item.filesize);
                   Log.d("Info：", Info);

                   DevFileInfo fileInfo = new DevFileInfo();
                   fileInfo.FilePath = filepath;
                   fileInfo.FileName =  Item.filename;
                   fileInfo.FileSize =  Item.filesize;
                   fileInfo.DownState = 1;
                   app.AddDownInfo(key,fileInfo);
               }
            }
        };
        public int getCount()
        {
            // TODO Auto-generated method stub
            return DataList.size();//数目
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {

            LayoutInflater inflater = DivDirActivity.this.getLayoutInflater();
            View view;

            if (convertView==null) {
                //因为getView()返回的对象，adapter会自动赋给ListView
                view = inflater.inflate(R.layout.diritem, null);
            }else{
                view=convertView;
                //Log.i("info","有缓存，不需要重新生成"+position);
            }

            TextView  tv1 = (TextView) view.findViewById(R.id.FileName);//找到Textviewname
            tv1.setText(DataList.get(position).filename);//设置参数

            Button btn_down = (Button)view.findViewById(R.id.btn_down);
            TextView  tv2 = (TextView) view.findViewById(R.id.FileSize);//找到Textviewage
            if(DataList.get(position).isdir==1) {
                tv2.setText("");//设置参数
                btn_down.setVisibility(View.INVISIBLE);
            }
            else {
                tv2.setText("大小：" + DataList.get(position).filesize);//设置参数
                btn_down.setVisibility(View.VISIBLE);
                btn_down.setTag(position);
                btn_down.setOnClickListener(BtnDownClickListener);

            }

            return view;
        }
        @Override
        public long getItemId(int position) {//取在列表中与指定索引对应的行id
            return 0;
        }
        @Override
        public Object getItem(int position) {//获取数据集中与指定索引对应的数据项
            return null;
        }

        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Log.d("点击：","点击");
            DirItem Item = DataList.get(position);
            Message msg = new Message();
            msg.what = 1;
            msg.obj  = Item;
            Activityhandler.sendMessage(msg);
        }
    }

    Handler Activityhandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
               if(msg.what==1) {
                   DirItem Item = (DirItem) msg.obj;
                   Jni51SeeSdk sdk = new Jni51SeeSdk();
                   ///是目录
                   if (Item.isdir == 1)
                   {
                           String ssss = "";
                           if (Item.Par.length() > 1)
                               ssss = Item.Par + "/";
                           ssss += Item.filename;
                           String strDir = sdk.JniGetDevFileList(devHandle, ssss);
                           Log.i("子目录：", Item.filename + ":" + strDir);
                           ListView lst_dir = (ListView) findViewById(R.id.lst_dir);
                           ListDirAdapter ap = (ListDirAdapter) lst_dir.getAdapter();
                           ap.Clear();
                           try {
                               JSONArray jsonObject = new JSONArray(strDir);
                               for (int i = 0; i < jsonObject.length(); i++) {
                                   JSONObject js = jsonObject.getJSONObject(i);
                                   DirItem It = new DirItem();
                                   It.Par = Item.filename;
                                   It.filename = js.get("filename").toString();
                                   String sss = js.get("filesize").toString();
                                   if(sss.length()>0)
                                   It.filesize = Integer.parseInt(sss);
                                   It.isdir = Integer.parseInt(js.get("isdir").toString());
                                   ap.Add(It);
                               }
                               ap.notifyDataSetChanged();
                           } catch (JSONException e) {

                           }
                   }else{

                   }
               }else if (msg.what==2)
               {
                   Jni51SeeSdk sdk = new Jni51SeeSdk();
                   devHandle=sdk.JniGetDevHandle(m_strDevId,m_strDevTurnIp);
                   final See51App app = (See51App)getApplication();
                   //全部监听(除音视频外)
                   //int ll =0xffffffff & 0xffffff0f;
                   sdk.JniAdd51SeeListener(devHandle, app,0xffffffff);
                   //devHandle=sdk.JniGetDevHandle("c8441c000014","39.108.213.89");
                   //devHandle=sdk.JniGetDevHandle("c21621000011","202.100.177.36");
                   //devHandle=sdk.JniGetDevHandle("c21521000037","202.100.177.36");
                   String strDir = sdk.JniGetDevDir(devHandle);
                   Log.d("设备目录", strDir);
                   ListView lst_dir = (ListView) findViewById(R.id.lst_dir);
                   ListDirAdapter ap = (ListDirAdapter) lst_dir.getAdapter();
                   try{
                       JSONArray jsonObject = new  JSONArray(strDir);
                       for(int i=0;i<jsonObject.length();i++)
                       {
                           JSONObject js=  jsonObject.getJSONObject(i);
                           DirItem It = new DirItem();
                           It.filename = js.get("filename").toString();
                           It.filesize = Integer.parseInt(js.get("filesize").toString());
                           It.isdir = Integer.parseInt(js.get("isdir").toString());
                           ap.Add(It);
                       }
                       ap.notifyDataSetChanged();
                       //jsonObject.
                   }catch (JSONException e)
                   {

                   }
               }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_div_dir);

       //[{"filename":"20190218","isdir":"1","filesize":"0"}]
        ListView lst_dir = (ListView) findViewById(R.id.lst_dir);
        ListDirAdapter ap = new ListDirAdapter();
        lst_dir.setAdapter(ap);
        lst_dir.setOnItemClickListener(ap);

        Bundle bundle = getIntent().getExtras();
        CharSequence DevId = bundle.getCharSequence("DevId");
        m_strDevId=DevId.toString();
        CharSequence DevTurnIp = bundle.getCharSequence("DevTurnIp");
        m_strDevTurnIp  = DevTurnIp.toString();
        Message msg = new Message();
        msg.what = 2;
        Activityhandler.sendMessageAtTime(msg, SystemClock.uptimeMillis()+500);
    }

}
